<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;
use App\Http\Controllers\Admin\Traits\AdminTrait;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Support\Arr;

class BaseRequest extends FormRequest
{
    use AdminTrait;

    protected  $rules = [
        'timeStamp' => 'required|integer',
        'sign' => 'required'
    ];

    protected  $errMsg = [
        'required' => ':attribute 必需',
        'integer' => ':attribute 必需为整形',
    ];

    protected  $attr = [
        'timeStamp'=> '时间戳',
        'sign'  => '签名'
    ];

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return $this->rules;
    }

    /*
    * 错误信息
    */
    public function messages()
    {

        return $this->errMsg ;
    }

    /*
     * 错误参数名
     */
    public function attributes()
    {

        return $this->attr;
    }

    //验证签名
    public function withValidator($validator)
    {

        $except = $this->exceptParams();
        $flag = $this->validateSign($except);
        $validator->after(function ($validator) use($flag) {
            if (!$flag) {
                //$validator->errors()->add('sign', '签名错误');
                return response()->json(['errcode'=>40013,'errmsg'=>'签名错误']);
            }

        });
    }

    protected  function exceptParams()
    {
        return [];
    }

    //验证签名
    protected function  validateSign($except = [])
    {
        array_push($except,'sign');

        $params = $this->validationData();
        $sign = Arr::get($params,'sign');
        $signArr = Arr::except($params,$except);

        return $this->check_sign($signArr,$sign);
    }

}
